<template>
  <div ref="wrapper">
    <slot></slot>
  </div>
</template>

<script>
import BSscroll from 'better-scroll'
export default {
  props: {
    probeType: {
      type: Number,
      default: 1
    },
    click: {
      type: Boolean,
      default: true
    },
    data: {
      type: Array,
      default: null
    },
    listenScroll: {
      type: Boolean,
      default: false
    },
    pullup: {
      type: Boolean,
      default: false
    },
    pulldown: {
      type: Boolean,
      default: false
    },
    // better scroll在滚动开始前会派发一个before scroll事件
    beforeScroll: {
      type: Boolean,
      default: false
    },
    // 刷新时间
    refreshDelay: {
      type: Number,
      default: 20
    }
  },
  watch: {
    data() {
      setTimeout(() => {
        this.refresh()
      }, 20)
    }
  },
  methods: {
    _initScroll() {
      if (!this.$refs.wrapper) {
        return
      }
      this.scroll = new BSscroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click
      })

      if (this.listenScroll) {
        let that = this
        this.scroll.on('scroll', (pos) => {
          that.$emit('scroll', pos)
        })
      }
      // 上拉加载
      if (this.pullup) {
        this.scroll.on('scrollEnd', () => {
          if (this.scroll.y <= this.scroll.maxScrollY + 50) {
            this.$emit('scrollToEnd')
          }
          // console.log(this.scroll.y)
        })
      }
      // 下拉刷新
      if (this.pulldown) {
        this.scroll.on('scroll', () => {
          if (this.scroll.y >= 30) {
            this.$emit('scrollToStart')
          }
          // console.log(this.scroll.y)
        })
      }
      // 滚动开始前的事件
      if (this.beforeScroll) {
        this.scroll.on('beforeScrollStart', () => {
          this.$emit('beforeScroll')
        })
      }
    },
    enable() {
      this.scroll && this.scroll.enable()
    },
    disable() {
      this.scroll && this.scroll.disable()
    },
    refresh() {
      this.scroll && this.scroll.refresh()
      // console.log('refresh')
    },
    scrollTo() {
      this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
    },
    scrollToElement() {
      this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
    }
  },
  mounted() {
    // 数据渲染好之后才初始化滚动
    setTimeout(() => {
      this._initScroll()
    }, this.refreshDelay)
    // this.$nextTick(() => {
    //   this._initScroll()
    // })
  }
}
</script>

<style>
</style>